package com.hdjk.view.fragment.main;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.hdjk.view.R;
import com.hdjk.view.activity.financial.FundListActivity;
import com.hdjk.view.activity.financial.ShopCarBuyActivity;
import com.hdjk.view.activity.personalcenter.OpenAccountActivity;
import com.hdjk.view.adapter.ShopCarListAdapter;
import com.hdjk.view.callback.CallBackListener;
import com.hdjk.view.entity.FundEntity;
import com.hdjk.view.entity.ShopCarEntity;
import com.hdjk.view.network.FundNetWork;
import com.hdjk.view.network.ShopCarNetWork;
import com.hdjk.view.util.ToastUtils;
import com.hdjk.view.util.UserTokenUtil;
import com.lst.projectlib.base.BaseFram;
import com.lst.projectlib.entity.Msg;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * 购物车Fragment
 * Created by sxy on 2017/11/1.
 */

public class ShopCarFragment extends BaseFram implements View.OnClickListener, SwipeRefreshLayout.OnRefreshListener {
    private boolean isCreate = false;
    private List<ShopCarEntity> mList;
    private ShopCarListAdapter mAdapter;
    private List<String> mSelectFundCodes;
    private ShopCarEntity updateEntity;
    // Content View Elements
    private SwipeRefreshLayout mSwipeLayout;
    private ImageView iv_empty;
    private TextView tv_add_fund;
    private ListView lv_data_list;
    private CheckBox cb_select_all;
    private TextView tv_del;
    private TextView tv_buy;
    private LinearLayout lin_bottom;
    // End Of Content View Elements

    private void bindViews(View view) {
        mSwipeLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipe_ly);
        iv_empty = (ImageView) view.findViewById(R.id.iv_empty);
        tv_add_fund = (TextView) view.findViewById(R.id.tv_add_fund);
        lv_data_list = (ListView) view.findViewById(R.id.lv_data_list);
        cb_select_all = (CheckBox) view.findViewById(R.id.cb_select_all);
        tv_del = (TextView) view.findViewById(R.id.tv_del);
        tv_buy = (TextView) view.findViewById(R.id.tv_buy);
        lin_bottom = (LinearLayout) view.findViewById(R.id.lin_bottom);
    }

    @Override
    protected View initView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_shop_car, container, false);
        bindViews(view);
        tv_add_fund.setOnClickListener(this);
        tv_del.setOnClickListener(this);
        tv_buy.setOnClickListener(this);
        cb_select_all.setOnClickListener(this);
        mSwipeLayout.setOnRefreshListener(this);
        mSwipeLayout.setColorSchemeResources(R.color.bg_common_red, R.color.bg_common_red,
                R.color.bg_common_red, R.color.bg_common_red);
        // 设置手指在屏幕下拉多少距离会触发下拉刷新
        mSwipeLayout.setDistanceToTriggerSync(200);
        return view;
    }

    @Override
    protected void initData() {
        mSelectFundCodes = new ArrayList<>();
        tv_buy.setEnabled(false);
        tv_buy.setBackgroundColor(getResources().getColor(R.color.gray_aaaaaaa));
        tv_buy.setText("购买");
        lv_data_list.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView absListView, int i) {

            }

            @Override
            public void onScroll(AbsListView absListView, int i, int i1, int i2) {
                boolean enable = false;
                if (lv_data_list != null && lv_data_list.getChildCount() > 0) {
                    // check if the first item of the list is visible
                    boolean firstItemVisible = lv_data_list.getFirstVisiblePosition() == 0;
                    // check if the top of the first item is visible
                    boolean topOfFirstItemVisible = lv_data_list.getChildAt(0).getTop() == 0;
                    // enabling or disabling the refresh layout
                    enable = firstItemVisible && topOfFirstItemVisible;
                }
                mSwipeLayout.setEnabled(enable);
            }
        });
        if (!isCreate) {
            getList();
            isCreate = true;
        }
    }

    private void getList() {

        mDialog.show();
        ShopCarNetWork.getShopCarList(UserTokenUtil.getToken(getContext()), new CallBackListener() {
            @Override
            public void onCallBackCompleted(Msg msg) {
                if (msg != null && msg.getSuccess() && msg.getData() != null && !TextUtils.isEmpty(msg.getData().toString())) {
                    mList = (List<ShopCarEntity>) msg.getData();
                    if (mList != null) {
                        String codelist = "";
                        for (int i = 0; i < mList.size(); i++) {
                            codelist = codelist + mList.get(i).getFundCode() + (i < (mList.size() - 1) ? "," : "");
                        }
                        JSONObject object = new JSONObject();
                        try {
                            object.put("fundCodes", codelist);
                            FundNetWork.getFundList(UserTokenUtil.getToken(getContext()), object.toString(), new CallBackListener() {
                                @Override
                                public void onCallBackCompleted(Msg msg) {
                                    if (mSwipeLayout.isRefreshing()) {
                                        mSwipeLayout.setRefreshing(false);
                                    }
                                    mDialog.dismiss();
                                    if (msg != null && msg.getSuccess() && msg.getData() != null && !TextUtils.isEmpty(msg.getData().toString())) {
                                        List<FundEntity> fundList = (ArrayList) msg.getData();
                                        if (fundList != null) {
                                            for (int i = 0; i < fundList.size(); i++) {
                                                FundEntity fundEntity = fundList.get(i);
                                                for (int j = 0; j < mList.size(); j++) {
                                                    ShopCarEntity shopCarEntity = mList.get(j);
                                                    if (fundEntity.getFundCode().equals(shopCarEntity.getFundCode())) {
                                                        shopCarEntity.setFund(fundEntity);
                                                    }
                                                }
                                            }
                                            if (mAdapter == null) {
                                                mAdapter = new ShopCarListAdapter(getContext(), new ShopCarListAdapter.OnMyItemClick() {
                                                    @Override
                                                    public void onDetailClick(View view, int position) {
                                                        ShopCarEntity entity = mList.get(position);
                                                        ImageView imageView = (ImageView) view.findViewById(R.id.iv_check);
                                                        if (entity.getShopCarSelect()) {
                                                            imageView.setImageDrawable(mContext.getResources().getDrawable(R.drawable.gwc_xuanzhong_dis));
                                                            entity.setShopCarSelect(false);
                                                            if (mSelectFundCodes.contains(entity.getFundCode()))
                                                                mSelectFundCodes.remove(entity.getFundCode());
                                                        } else {
                                                            imageView.setImageDrawable(mContext.getResources().getDrawable(R.drawable.gwc_xuanzhong_sel));
                                                            entity.setShopCarSelect(true);
                                                            if (!mSelectFundCodes.contains(entity.getFundCode()))
                                                                mSelectFundCodes.add(entity.getFundCode());
                                                        }
                                                        boolean isAllSel = true;
                                                        int selCount = 0;
                                                        for (ShopCarEntity shopCarEntity : mList) {
                                                            if (!shopCarEntity.getShopCarSelect()) {
                                                                isAllSel = false;
                                                            } else {
                                                                selCount++;
                                                            }
                                                        }
                                                        if (isAllSel) {
                                                            cb_select_all.setChecked(true);
                                                        } else {
                                                            cb_select_all.setChecked(false);
                                                        }
                                                        if (selCount > 0) {
                                                            tv_buy.setEnabled(true);
                                                            tv_buy.setBackgroundDrawable(getResources().getDrawable(R.drawable.sure_button_selector));
                                                            tv_buy.setText("购买(" + selCount + ")");
                                                        } else {
                                                            tv_buy.setEnabled(false);
                                                            tv_buy.setBackgroundColor(getResources().getColor(R.color.gray_aaaaaaa));
                                                            tv_buy.setText("购买");
                                                        }
                                                    }

                                                    @Override
                                                    public void onEditTextFinish(View view, int position) {
                                                        updateEntity = mList.get(position);
                                                        EditText editText = (EditText) view.findViewById(R.id.et_money);
                                                        if (!TextUtils.isEmpty(editText.getText().toString())) {
                                                            updateEntity.setAmount(editText.getText().toString());
                                                        }
                                                        if (delayRun != null) {
                                                            //每次editText有变化的时候，则移除上次发出的延迟线程
                                                            mHandler.removeCallbacks(delayRun);
                                                        }
                                                        //延迟1000ms，如果不再输入字符，则执行该线程的run方法
                                                        mHandler.postDelayed(delayRun, 1000);
                                                    }
                                                });
                                                mAdapter.setDataList(mList);
                                                lv_data_list.setAdapter(mAdapter);
                                            } else {
                                                mAdapter.setDataList(mList);
                                                lv_data_list.setAdapter(mAdapter);
                                            }
                                            if (mList.size() < 1) {
                                                lv_data_list.setVisibility(View.GONE);
                                                lin_bottom.setVisibility(View.GONE);
                                                iv_empty.setVisibility(View.VISIBLE);
                                                tv_add_fund.setVisibility(View.VISIBLE);
                                            } else {
                                                lv_data_list.setVisibility(View.VISIBLE);
                                                lin_bottom.setVisibility(View.VISIBLE);
                                                iv_empty.setVisibility(View.GONE);
                                                tv_add_fund.setVisibility(View.GONE);
                                                mSelectFundCodes.clear();
                                                tv_buy.setEnabled(false);
                                                tv_buy.setBackgroundColor(getResources().getColor(R.color.gray_aaaaaaa));
                                                tv_buy.setText("购买");
                                            }
                                            cb_select_all.setChecked(false);
                                        }
                                    }
                                }

                                @Override
                                public void onCallBackError(Msg msg) {
                                    mDialog.cancel();
                                    if (mSwipeLayout.isRefreshing()) {
                                        mSwipeLayout.setRefreshing(false);
                                    }
                                }
                            });
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                } else {
                    mDialog.dismiss();
                    if (mSwipeLayout.isRefreshing()) {
                        mSwipeLayout.setRefreshing(false);
                    }
                }
            }

            @Override
            public void onCallBackError(Msg msg) {
                mDialog.cancel();
                if (mSwipeLayout.isRefreshing()) {
                    mSwipeLayout.setRefreshing(false);
                }
            }
        });

    }

    private Handler mHandler = new Handler();
    /**
     * 延迟线程，看是否还有下一个字符输入
     */
    private Runnable delayRun = new Runnable() {

        @Override
        public void run() {
            //在这里调用服务器的接口，获取数据
            editShopCar();
        }
    };
    int time = 0;

    private void editShopCar() {
        if (!TextUtils.isEmpty(updateEntity.getAmount())) {
            JSONObject object = new JSONObject();
            try {
                object.put("Id", updateEntity.getId());
                object.put("FundCode", updateEntity.getFundCode());
                object.put("FundName", updateEntity.getFundName());
                object.put("Amount", updateEntity.getAmount());
                ShopCarNetWork.editShopCar(UserTokenUtil.getToken(getContext()), object.toString(), new CallBackListener() {
                    @Override
                    public void onCallBackCompleted(Msg msg) {
                        if (msg != null && msg.getSuccess()) {
//                            ToastUtils.showShortToast(getContext(), "修改成功");
                            time = 0;
                        } else {
//                            if (msg != null && !TextUtils.isEmpty(msg.getMsg()) && !"null".equals(msg.getMsg())) {
//                                ToastUtils.showShortToast(getContext(), msg.getMsg());
//                            } else {
//                                ToastUtils.showShortToast(getContext(), "修改失败");
//                            }
                            time++;
                            if (time < 2) {
                                editShopCar();
                            } else {
                                time = 0;
                            }
                        }
                    }

                    @Override
                    public void onCallBackError(Msg msg) {

                    }
                });
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 是否显示当前页
     *
     * @param isVisibleToUser
     */
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isCreate) {//fragment是否创建
            if (isVisibleToUser) {
                if (!UserTokenUtil.isLogin(getContext())) {
                    ToastUtils.showShortToast(getContext(), "您未登陆，请先登陆");
                    if (mList != null) {
                        mList.clear();
                    }
                    lv_data_list.setVisibility(View.GONE);
                    lin_bottom.setVisibility(View.GONE);
                    iv_empty.setVisibility(View.VISIBLE);
                    tv_add_fund.setVisibility(View.VISIBLE);
                } else {
                    lv_data_list.setVisibility(View.VISIBLE);
                    lin_bottom.setVisibility(View.VISIBLE);
                    iv_empty.setVisibility(View.GONE);
                    tv_add_fund.setVisibility(View.GONE);
                    getList();
                }
            } else {

            }
        }
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    private void delete(String codes) {
        mDialog.show();
        ShopCarNetWork.delShopCar(UserTokenUtil.getToken(getContext()), codes, new CallBackListener() {
            @Override
            public void onCallBackCompleted(Msg msg) {
                if (mDialog.isShowing())
                    mDialog.dismiss();
                if (msg != null && msg.getSuccess()) {
//                    ToastUtils.showShortToast(getContext(), "删除成功");
                    mSelectFundCodes.clear();
                    getList();
                } else {
                    if (msg != null && !TextUtils.isEmpty(msg.getMsg()) && !"null".equals(msg.getMsg())) {
                        ToastUtils.showShortToast(getContext(), msg.getMsg());
                    } else {
                        ToastUtils.showShortToast(getContext(), "删除失败");
                    }
                }
            }

            @Override
            public void onCallBackError(Msg msg) {
                if (mDialog.isShowing())
                    mDialog.dismiss();
            }
        });
    }

    @Override
    public void onClick(View view) {
        Intent intent;
        switch (view.getId()) {
            case R.id.tv_add_fund:
                intent = new Intent(getContext(), FundListActivity.class);
                startActivityForResult(intent, 88);
                break;
            case R.id.tv_del:
                if (mSelectFundCodes == null || mSelectFundCodes.size() < 1) {
                    ToastUtils.showShortToast(getContext(), "请选择要删除的基金");
                    return;
                }
                String codes = "[";
                for (int i = 0; i < mSelectFundCodes.size(); i++) {
                    codes = codes + "\"" + mSelectFundCodes.get(i) + "\"" + (i < mSelectFundCodes.size() - 1 ? "," : "]");
                }
                delete(codes);
                break;
            case R.id.tv_buy:
                if (UserTokenUtil.isOpenAccount(getContext())) {
                    List<ShopCarEntity> list = new ArrayList<>();
                    for (String s : mSelectFundCodes) {
                        for (ShopCarEntity entity : mList) {
                            if (entity.getFundCode().equals(s)) {
                                list.add(entity);
                            }
                        }
                    }
                    for (ShopCarEntity entity : list) {
                        String money = entity.getAmount() == null ? "" : entity.getAmount().toString();
                        FundEntity fundEntity = entity.getFund();
                        if (TextUtils.isEmpty(money) || Double.parseDouble(money) <= 0) {
                            ToastUtils.showShortToast(getContext(), fundEntity.getFundName() + "请输入购买金额");
                            return;
                        }
                    }
                    intent = new Intent(getContext(), ShopCarBuyActivity.class);
                    intent.putExtra("list", (Serializable) list);
                    startActivityForResult(intent, 741);
                } else {
                    ToastUtils.showShortToast(getContext(), "请先开户");
                    intent = new Intent(getContext(), OpenAccountActivity.class);
                    startActivity(intent);
                }
                break;
            case R.id.cb_select_all:
                if (mList != null) {
                    for (ShopCarEntity entity : mList) {
                        if (cb_select_all.isChecked()) {
                            mSelectFundCodes.clear();
                            for (ShopCarEntity shopCarEntity : mList) {
                                mSelectFundCodes.add(shopCarEntity.getFundCode());
                            }
                            entity.setShopCarSelect(true);
                            tv_buy.setEnabled(true);
                            tv_buy.setBackgroundDrawable(getResources().getDrawable(R.drawable.sure_button_selector));
                            tv_buy.setText("购买(" + mList.size() + ")");
                        } else {
                            mSelectFundCodes.clear();
                            entity.setShopCarSelect(false);
                            tv_buy.setEnabled(false);
                            tv_buy.setBackgroundColor(getResources().getColor(R.color.gray_aaaaaaa));
                            tv_buy.setText("购买");
                        }
                    }
                    if (mAdapter != null) {
                        mAdapter.setDataList(mList);
                        mAdapter.notifyDataSetChanged();
                    }
                }
                break;
        }
    }

    @Override
    public void onRefresh() {
        getList();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 88) {
            if (UserTokenUtil.isLogin(getContext())) {
                lv_data_list.setVisibility(View.VISIBLE);
                lin_bottom.setVisibility(View.VISIBLE);
                iv_empty.setVisibility(View.GONE);
                tv_add_fund.setVisibility(View.GONE);
                getList();
            }
        }
        if (requestCode == 741 && resultCode == 741) {
            String codes = "[";
            for (int i = 0; i < mSelectFundCodes.size(); i++) {
                codes = codes + "\"" + mSelectFundCodes.get(i) + "\"" + (i < mSelectFundCodes.size() - 1 ? "," : "]");
            }
            delete(codes);
        }
    }
}
